package cn.lovemmd.model.admin.controller;

import cn.lovemmd.model.admin.common.PageResult;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.lovemmd.model.admin.common.Result;
import cn.lovemmd.model.admin.entity.Code;
import cn.lovemmd.model.admin.service.CodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/v2/code")
@Api(tags = "授权码管理V2")
@Validated
@RequiredArgsConstructor
public class CodeControllerV2 {

    private static final Logger log = LoggerFactory.getLogger(CodeControllerV2.class);

    private final CodeService codeService;

    @GetMapping(value = "/list", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("分页查询授权码列表")
    public ResponseEntity<String> list(
            @ApiParam("当前页码") @RequestParam(defaultValue = "1") Long page,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") Long size
    ) {
        try {
            Page<Code> p = new Page<>(page, size);
            Page<Code> result = codeService.page(p, new LambdaQueryWrapper<>());
            return ResponseEntity.ok(JSON.toJSONString(Result.success(new PageResult<>(result.getRecords(), result.getTotal(), result.getCurrent(), result.getSize()))));
        } catch (Exception e) {
            log.error("查询授权码列表失败", e);
            return ResponseEntity.ok(JSON.toJSONString(Result.error("查询授权码列表失败：" + e.getMessage())));
        }
    }

    @PostMapping(value = "/add", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("新增授权码")
    public ResponseEntity<String> add(@ApiParam("授权码") @RequestParam String cCode) {
        try {
            boolean ok = codeService.addCode(cCode);
            return ResponseEntity.ok(JSON.toJSONString(ok ? Result.success("新增成功") : Result.error("新增失败")));
        } catch (Exception e) {
            log.error("新增授权码失败", e);
            return ResponseEntity.ok(JSON.toJSONString(Result.error("新增授权码失败：" + e.getMessage())));
        }
    }

    @DeleteMapping(value = "/{cId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("删除授权码")
    public ResponseEntity<String> delete(@PathVariable Long cId) {
        try {
            boolean ok = codeService.deleteCode(cId);
            return ResponseEntity.ok(JSON.toJSONString(ok ? Result.success("删除成功") : Result.error("删除失败")));
        } catch (Exception e) {
            log.error("删除授权码失败", e);
            return ResponseEntity.ok(JSON.toJSONString(Result.error("删除授权码失败：" + e.getMessage())));
        }
    }
}
